<?php
//模型
class CoachModel extends MY_Model {
	function __construct(){
		parent::__construct();
		$this->table = 'coach';
		$this->lists = array();
	}
	
	
	function mobile_getinfo($mobile){
		$sql  = "select * from ".$this->db->dbprefix.$this->table." where mobile='{$mobile}' ";
		$query = $this->db->query($sql);
		$row = $query->row_array();		
		return $row;
	}
	function openid_getinfo($openid){
		$sql  = "select * from ".$this->db->dbprefix.$this->table." where openid='{$openid}' ";
		$query = $this->db->query($sql);
		$row = $query->row_array();		
		return $row;
	}
	
	function get_info($cid){
		$sql  = "select * from ".$this->db->dbprefix.$this->table." where id='{$cid}' ";
		$query = $this->db->query($sql);
		$row = $query->row_array();		
		if(!$row ){
			return false;
		}
		unset($row['openid']);
		$row['addtime'] = date('Y-m-d H:i:s',$row['addtime']);
		return $row;
	}
	
	function get_info_c($id){
		if(isset($lists[$id])){
			return $lists[$id];
		}
		
		$info = $this->get_info($id);
		$lists[$id] = $info;
		return $info;
	}
	
	//openid获取token
	function openid_get_token($openid){

		
		$tt = $this->lock_url($openid,'123456');
		$base = base64_encode($tt);
		
		
		return $base;
	}
	
	//openid获取token
	function token_get_openid($token){

		$base = base64_decode($token);
		$openid = $this->unlock_url($base,'123456');


		
		return $openid;
	}
	
	//加密函数
	function lock_url($txt,$key='slinw'){
	  if(empty($txt)){
		return '';
	  }
	  $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
	  $nh = rand(0,64);
	  $ch = $chars[$nh];
	  $mdKey = md5($key.$ch);
	  $mdKey = substr($mdKey,$nh%8, $nh%8+7);
	  $txt = base64_encode($txt);
	  $tmp = '';
	  $i=0;$j=0;$k = 0;
	  for ($i=0; $i<strlen($txt); $i++) {
		$k = $k == strlen($mdKey) ? 0 : $k;
		$j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%64;
		$tmp .= $chars[$j];
	  }
	  return urlencode($ch.$tmp);
	}
	//解密函数
	function unlock_url($txt,$key='slinw'){
	  if(empty($txt)){
		return '';
	  }
	  $txt = urldecode($txt);
	  $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
	  $ch = $txt[0];
	  $nh = strpos($chars,$ch);
	  $mdKey = md5($key.$ch);
	  $mdKey = substr($mdKey,$nh%8, $nh%8+7);
	  $txt = substr($txt,1);
	  $tmp = '';
	  $i=0;$j=0; $k = 0;
	  for ($i=0; $i<strlen($txt); $i++) {
		$k = $k == strlen($mdKey) ? 0 : $k;
		$j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]);
		while ($j<0) $j+=64;
		$tmp .= $chars[$j];
	  }
	  return base64_decode($tmp);
	}
	
	function mobile_is_exits($mobile){
		$sql = "select * from ".$this->db->dbprefix.$this->table." where mobile ='{$mobile}' limit 1";
		$query = $this->db->query($sql);
		$row = $query->row_array();		
		if(!$row){
			return false;
		}
		return true;
	}
}

